package com.cib.icarus.sensitive;

import com.cib.icarus.core.utils.dfa.DFAProvider;
import com.cib.icarus.core.utils.dfa.DfaMeta;
import com.cib.icarus.core.utils.internals.CalculateUtils;
import com.cib.icarus.core.utils.internals.StrUtils;

import java.util.List;
import java.util.Set;

/**
 * 敏感词工具类
 *
 * @author goomba
 */
public class SensitiveWordUtils {

    /**
     * 对给定文本中的敏感词进行脱敏处理
     *
     * @param sensitiveWords 敏感词集合
     * @param target         待处理的文本
     * @param placeholder    脱敏替换符
     * @return 脱敏后的文本
     */
    public static String desensitize(Set<String> sensitiveWords, String target, String placeholder) {
        List<DfaMeta> sensitiveWordList = DFAProvider.create(sensitiveWords).quickSearch(target);
        for (DfaMeta sensitiveWord : sensitiveWordList) {
            int repeatCnt = CalculateUtils.pageCnt(sensitiveWord.getMatchKey().length(), placeholder.length());
            String placeholderStr = StrUtils.repeat(repeatCnt, placeholder);
            target = target.replace(sensitiveWord.getMatchKey(), placeholderStr);
        }
        return target;
    }

    /**
     * 检查目标字符串中是否包含敏感词汇
     * 该方法使用DFA算法快速搜索目标字符串中的敏感词汇
     *
     * @param sensitiveWords 敏感词汇集合
     * @param target         目标字符串
     * @return 如果目标字符串中包含敏感词汇，则返回true；否则返回false
     */
    public static boolean contains(Set<String> sensitiveWords, String target) {
        List<DfaMeta> sensitiveWordList = DFAProvider.create(sensitiveWords).quickSearch(target);
        return !sensitiveWordList.isEmpty();
    }


}
